

from qiniu import BucketManager
from qiniu import Auth, put_file, etag
import qiniu.config
from qiniu import build_batch_delete
class Qiniu():

    def __init__(self,ak,sk):
        self.ak = ak
        self.sk = sk
        self.q = Auth(ak,sk)
        qiniu.config.set_default(connection_timeout=120)



    def qiniu_put_file(self,bucket_name,localfile,key):
        #qiniu.config.get_default('default_zone').up_host = 'http://free-qvm-z0-xs.qiniup.com' # 修改上传地址

        token = self.q.upload_token(bucket_name, key, 3600)   # 生成上传 Token，可以指定过期时间等
        ret, info = put_file(token, key, localfile)
        return info.status_code

    #获取七牛文件列表
    def bucket_file_list(self,bucket_name,prefix=None,limit=10,marker = None):

        bucket = BucketManager(self.q)
        delimiter = None # 列举出除'/'的所有文件以及以'/'为分隔的所有前缀
        ret, eof, info = bucket.list(bucket_name, prefix, marker, limit, delimiter)

        return ret.get('items'),ret.get('marker')

    def delete_after_days(self,bucket_name, key, days):
        '''
        指定文件在多少天后删除
        :param bucket_name:
        :param key: 文件名称
        :param days: 指定天数
        :return:
        '''
        bucket = BucketManager(self.q)
        ret, info = bucket.delete_after_days(bucket_name, key, str(days))
        return info.status_code


    def delete_file(self,bucket_name,key):
        '''
        单个删除文件
        :param bucket_name:
        :param key:
        :return:
        '''
        bucket = BucketManager(self.q) # 初始化BucketManager
        ret, info = bucket.delete(bucket_name, key)
        return info.status_code

    def delete_keys(self,bucket_name,keys,r=False):
        '''
        批量删除文件
        :param bucket_name:
        :param keys:
        :param r:
        :return:
        '''
        bucket = BucketManager(self.q) # 初始化BucketManager
        ops = build_batch_delete(bucket_name, keys)
        ret, info = bucket.batch(ops)

        if r:
            return ret,info
        else:
            return info.status_code